﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum BlockColor
{
    Blue,
    Red,
}

public class ColorBlock : Ground
{
    public BlockColor color;

    MaterialFloatAnimation floatAnimation;
    Collider cld;

    protected override void Awake()
    {
        base.Awake();
        floatAnimation = GetComponent<MaterialFloatAnimation>();
        cld = GetComponent<Collider>();
        cld.enabled = false;

        floatAnimation.BindEndAction(0, () => 
        {
            cld.enabled = true;
            StartCoroutine(ReBuildNav());
            ColorChange.instance.SetBtnEnable(true);
        });

        floatAnimation.BindEndAction(1, () =>
        {
            ColorChange.instance.SetBtnEnable(true);
        });

        if (color == BlockColor.Red)
        {
            MessageManager.BindAction(MsgKey.ShowGreenBlock, ShowTheBlock);
            MessageManager.BindAction(MsgKey.ShowBlueBlock, HideTheBlock);
            MessageManager.BindAction(MsgKey.ShowDefaultBlock, HideTheBlock);
        }
        else if(color == BlockColor.Blue)
        {
            MessageManager.BindAction(MsgKey.ShowBlueBlock, ShowTheBlock);
            MessageManager.BindAction(MsgKey.ShowGreenBlock, HideTheBlock);
            MessageManager.BindAction(MsgKey.ShowDefaultBlock, HideTheBlock);
        }
    }

    void ShowTheBlock()
    {
        ColorChange.instance.SetBtnEnable(false);

        if (gameObject.activeSelf && !cld.enabled)
        {
            floatAnimation.Play(0);
        }
        else
        {
            GetComponentInChildren<Renderer>().material.SetFloat("Strength_", 1);
            cld.enabled = true;
            ColorChange.instance.SetBtnEnable(true);
        }
        print("gameObject.activeSelf && !cld.enabled " + (gameObject.activeSelf && !cld.enabled));
    }

    void HideTheBlock()
    {
        ColorChange.instance.SetBtnEnable(false);

        if (gameObject.activeSelf && cld.enabled)
        {
            floatAnimation.Play(1);
            cld.enabled = false;
            StartCoroutine(ReBuildNav());
        }
        else
        {
            GetComponentInChildren<Renderer>().material.SetFloat("Strength_", 0.3f);
            cld.enabled = false;
            ColorChange.instance.SetBtnEnable(true);
        }
    }

    IEnumerator ReBuildNav()
    {
        yield return new WaitForFixedUpdate();
        LevelManager.instance.BuildNavMesh();
    }
}
